// V-backend/src/controllers/orderController.js
const db = require('../models');
const Order = db.Order;
const OrderItem = db.OrderItem;
const Product = db.Product;
const Cart = db.Cart;
const { Op } = require('sequelize');

// 生成订单号的辅助函数
const generateOrderNumber = () => {
  const timestamp = new Date().getTime();
  const random = Math.floor(Math.random() * 1000);
  return `ORD${timestamp}${random}`;
};

// 创建订单
exports.createOrder = async (req, res) => {
  const transaction = await db.sequelize.transaction();
  
  try {
    const audience_id = req.user.userId;
    const { shipping_address, recipient_name, recipient_phone, note, cart_ids } = req.body;

    // 验证输入
    if (!shipping_address || !recipient_name || !recipient_phone) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '收货地址、收货人姓名和电话不能为空'
      });
    }

    // 获取购物车商品
    let cartItems;
    if (cart_ids && cart_ids.length > 0) {
      // 从指定购物车项创建订单
      cartItems = await Cart.findAll({
        where: { 
          cart_id: cart_ids,
          audience_id 
        },
        include: [{
          model: Product,
          as: 'product',
          where: { status: 'active' }
        }]
      });
    } else {
      // 从整个购物车创建订单
      cartItems = await Cart.findAll({
        where: { audience_id },
        include: [{
          model: Product,
          as: 'product',
          where: { status: 'active' }
        }]
      });
    }

    if (!cartItems || cartItems.length === 0) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '购物车为空或商品已下架'
      });
    }

    // 计算总金额并验证库存
    let totalAmount = 0;
    const orderItemsData = [];

    for (const cartItem of cartItems) {
      if (cartItem.quantity > cartItem.product.stock_quantity) {
        await transaction.rollback();
        return res.status(400).json({
          code: 400,
          success: false,
          message: `商品 "${cartItem.product.product_name}" 库存不足，当前库存 ${cartItem.product.stock_quantity}`
        });
      }

      const subtotal = cartItem.quantity * parseFloat(cartItem.product.price);
      totalAmount += subtotal;

      orderItemsData.push({
        product_id: cartItem.product_id,
        product_name: cartItem.product.product_name,
        product_price: cartItem.product.price,
        quantity: cartItem.quantity,
        subtotal: subtotal
      });
    }

    // 手动生成订单号
    const orderNumber = generateOrderNumber();
    console.log('🔢 手动生成的订单号:', orderNumber);

    // 创建订单 - 手动设置订单号
    const order = await Order.create({
      audience_id,
      order_number: orderNumber,
      total_amount: totalAmount,
      shipping_address,
      recipient_name,
      recipient_phone,
      note,
      status: 'pending',
      payment_status: 'pending'
    }, { transaction });

    // 创建订单项
    for (const itemData of orderItemsData) {
      await OrderItem.create({
        order_id: order.order_id,
        ...itemData
      }, { transaction });

      // 减少商品库存
      await Product.decrement('stock_quantity', {
        by: itemData.quantity,
        where: { product_id: itemData.product_id },
        transaction
      });

      // 增加商品销量
      await Product.increment('sales_count', {
        by: itemData.quantity,
        where: { product_id: itemData.product_id },
        transaction
      });
    }

    // 清空购物车
    if (cart_ids && cart_ids.length > 0) {
      await Cart.destroy({
        where: { 
          cart_id: cart_ids,
          audience_id 
        },
        transaction
      });
    } else {
      await Cart.destroy({
        where: { audience_id },
        transaction
      });
    }

    await transaction.commit();

    // 返回完整的订单信息
    const orderWithDetails = await Order.findByPk(order.order_id, {
      include: [
        {
          model: OrderItem,
          as: 'items',
          include: [{
            model: Product,
            as: 'product',
            attributes: ['product_id', 'cover_image']
          }]
        }
      ]
    });

    res.status(201).json({
      code: 201,
      success: true,
      message: '订单创建成功',
      data: orderWithDetails
    });

  } catch (error) {
    await transaction.rollback();
    console.error('创建订单失败:', error);
    
    // 提供更详细的错误信息
    if (error.name === 'SequelizeValidationError') {
      const validationErrors = error.errors.map(err => ({
        field: err.path,
        message: err.message
      }));
      
      return res.status(400).json({
        code: 400,
        success: false,
        message: '数据验证失败',
        errors: validationErrors
      });
    }
    
    res.status(500).json({
      code: 500,
      success: false,
      message: '创建订单失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取用户订单列表
exports.getUserOrders = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;

    const where = { audience_id };
    if (status) where.status = status;

    const orders = await Order.findAndCountAll({
      where,
      include: [
        {
          model: OrderItem,
          as: 'items',
          include: [{
            model: Product,
            as: 'product',
            attributes: ['product_id', 'cover_image']
          }]
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      code: 200,
      success: true,
      message: '获取订单列表成功',
      data: orders.rows,
      pagination: {
        current: parseInt(page),
        total: orders.count,
        pages: Math.ceil(orders.count / limit),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '获取订单列表失败'
    });
  }
};

// 获取订单详情 - 修复版本
exports.getOrderById = async (req, res) => {
  try {
    const audience_id = req.user.userId;
    
    // 使用正确的参数名 orderId
    const { orderId } = req.params;
    console.log('🔍 查询订单详情 - 参数:', { orderId, audience_id });

    // 验证 orderId 参数
    if (!orderId || isNaN(parseInt(orderId))) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '订单ID参数无效'
      });
    }

    const orderIdNum = parseInt(orderId);

    // 先查询基础订单信息
    const order = await Order.findOne({
      where: { order_id: orderIdNum, audience_id }
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '订单不存在'
      });
    }

    // 单独查询订单项
    const orderItems = await OrderItem.findAll({
      where: { order_id: orderIdNum },
      include: [{
        model: Product,
        as: 'product',
        attributes: ['product_id', 'cover_image', 'product_name', 'price']
      }]
    });

    // 组合数据
    const orderWithItems = {
      ...order.toJSON(),
      items: orderItems
    };

    console.log('✅ 订单详情查询成功:', order.order_id);

    res.json({
      code: 200,
      success: true,
      message: '获取订单详情成功',
      data: orderWithItems
    });
  } catch (error) {
    console.error('❌ 获取订单详情失败:', error);
    
    res.status(500).json({
      code: 500,
      success: false,
      message: '获取订单详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 取消订单
exports.cancelOrder = async (req, res) => {
  const transaction = await db.sequelize.transaction();
  
  try {
    const audience_id = req.user.userId;
    const { order_id } = req.params;

    const order = await Order.findOne({
      where: { 
        order_id, 
        audience_id,
        status: ['pending', 'paid'] // 只能取消待支付或已支付的订单
      },
      include: [{
        model: OrderItem,
        as: 'items'
      }]
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '订单不存在或无法取消'
      });
    }

    // 恢复库存
    for (const item of order.items) {
      await Product.increment('stock_quantity', {
        by: item.quantity,
        where: { product_id: item.product_id },
        transaction
      });

      // 减少销量
      await Product.decrement('sales_count', {
        by: item.quantity,
        where: { product_id: item.product_id },
        transaction
      });
    }

    // 更新订单状态
    order.status = 'cancelled';
    if (order.payment_status === 'paid') {
      order.payment_status = 'refunded';
    }
    await order.save({ transaction });

    await transaction.commit();

    res.json({
      code: 200,
      success: true,
      message: '订单取消成功',
      data: order
    });
  } catch (error) {
    await transaction.rollback();
    console.error('取消订单失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '取消订单失败'
    });
  }
};

// 模拟支付
// 模拟支付 - 修复版本
exports.processPayment = async (req, res) => {
  const transaction = await db.sequelize.transaction();
  
  try {
    const audience_id = req.user.userId;
    const { orderId } = req.params;

    console.log('💰 开始支付处理:', { orderId, audience_id });

    // 验证 orderId 参数
    if (!orderId || isNaN(parseInt(orderId))) {
      return res.status(400).json({
        code: 400,
        success: false,
        message: '订单ID参数无效'
      });
    }

    const orderIdNum = parseInt(orderId);

    const order = await Order.findOne({
      where: { 
        order_id: orderIdNum, 
        audience_id,
        status: 'pending',
        payment_status: 'pending'
      }
    });

    if (!order) {
      console.log('❌ 订单不存在或无法支付:', orderIdNum);
      return res.status(404).json({
        code: 404,
        success: false,
        message: '订单不存在或无法支付'
      });
    }

    console.log('✅ 找到订单，开始支付:', order.order_id);

    // 模拟支付处理
    order.status = 'paid';
    order.payment_status = 'paid';
    order.payment_method = 'alipay'; // 模拟支付方式
    order.paid_at = new Date();
    
    console.log('🔄 更新订单状态...');
    await order.save({ transaction });

    await transaction.commit();
    console.log('✅ 支付处理成功:', order.order_id);

    res.json({
      code: 200,
      success: true,
      message: '支付成功',
      data: order
    });
  } catch (error) {
    await transaction.rollback();
    console.error('❌ 支付处理失败:', error);
    
    // 提供更详细的错误信息
    res.status(500).json({
      code: 500,
      success: false,
      message: '支付处理失败',
      error: process.env.NODE_ENV === 'development' ? {
        message: error.message,
        stack: error.stack,
        details: error
      } : undefined
    });
  }
};

// 获取订单统计信息
exports.getOrderStats = async (req, res) => {
  try {
    const audience_id = req.user.userId;

    const stats = await Order.findAll({
      where: { audience_id },
      attributes: [
        'status',
        [db.sequelize.fn('COUNT', db.sequelize.col('order_id')), 'count']
      ],
      group: ['status']
    });

    const totalOrders = await Order.count({
      where: { audience_id }
    });

    const totalSpent = await Order.sum('total_amount', {
      where: { 
        audience_id,
        status: ['paid', 'completed']
      }
    });

    res.json({
      code: 200,
      success: true,
      message: '获取订单统计成功',
      data: {
        stats,
        totalOrders,
        totalSpent: totalSpent || 0
      }
    });
  } catch (error) {
    console.error('获取订单统计失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: '获取订单统计失败'
    });
  }
};